package com.zwcl.example.cloudprovider.service.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwcl.common.core.utils.JsonUtils;
import com.zwcl.common.mybatis.service.impl.BaseServiceImpl;
import com.zwcl.example.facade.dto.CloudPaperDto;
import com.zwcl.example.facade.entity.CloudPaper;
import com.zwcl.example.cloudprovider.mapper.CloudPaperMapper;
import com.zwcl.example.cloudprovider.service.CloudPaperService;
import com.zwcl.example.facade.vo.CloudPaperVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 *  增加二级缓存的例子
 * </p>
 *
 * @author xieyongping
 * @since 2020-11-14
 */
@Service
@Slf4j
public class CloudPaperServiceImpl extends BaseServiceImpl<CloudPaperMapper, CloudPaper> implements CloudPaperService {

    @Autowired
    private CloudPaperMapper cloudPaperMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 定义一个是String类型的远程缓存
    @CreateCache(name ="zwcl:paper:name:", expire = 120, cacheType = CacheType.REMOTE)
    private Cache<String, String> paperNameCache;
    // 定义一个是User对象的二级缓存(本地+远程)
    @CreateCache(name ="zwcl:paper:", localExpire = 60, localLimit = 100, expire = 120, cacheType = CacheType.BOTH)
    private Cache<String, CloudPaper> paperCache;


    @Override
    public Page<CloudPaperVo> showPlanList(Page<CloudPaperVo> page, CloudPaperDto dto) {
        Page<CloudPaperVo> pageList= cloudPaperMapper.showPaperList(page,dto);
        return pageList;
    }

    @Override
    public CloudPaper getPaperById(Long id) {
        CloudPaper glassPaper = paperCache.computeIfAbsent(id.toString(), paper -> {
            return this.getById(id);
        });

        paperNameCache.put(id.toString(),glassPaper.getName());

        redisTemplate.opsForValue().set("zwcl:paper:redis:"+id.toString(), glassPaper, 3, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("zwcl:paper:strredis:"+id.toString(), JsonUtils.objectToJson(glassPaper), 3, TimeUnit.MINUTES);

        CloudPaper paper1= (CloudPaper) redisTemplate.opsForValue().get("zwcl:paper:redis:"+id.toString());
        log.info("试卷1：{}",paper1.toString());
        String  paper2=  stringRedisTemplate.opsForValue().get("zwcl:paper:strredis:"+id.toString());
        log.info("试卷2：{}"+paper2);
        return glassPaper;
    }

}
